﻿using Anley.DomainDrivenDesign.Contract.Enums;

namespace Anley.DomainDrivenDesign.Contract.Helper;

/// <summary>
/// 随机帮助类
/// </summary>
public class RandomHelper
    : IRandomHelper
{
    private const string _numberCharacters = "0123456789";
    private const string _lowercaseCharacters = "abcdefghijklmnopqrstuvwxyz";
    private const string _uppercaseCharacters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private const string _specialCharacters = "-_.~";

    // 生成数字字符串
    public string GenerateNumberString(
        int length)
    {
        var numbers = new char[length];
        var randomBytes = new byte[length * 2];
        // 填充随机值
        using var rng = RandomNumberGenerator.Create();
        rng.GetBytes(randomBytes);
        // 将字节映射到0-9
        for (int i = 0; i < length; i++)
            numbers[i] = (char)('0' + randomBytes[i] % 10);
        // 返回字符串
        return new string(numbers);
    }

    // 生成复杂字符串
    public string GenerateComplexString(
        CharacterType characterType,
        int length)
    {
        // 要使用的字符串
        var characterList = new List<string>();
        if (characterType.HasFlag(CharacterType.Number))
            characterList.Add(_numberCharacters);
        if (characterType.HasFlag(CharacterType.LowerCase))
            characterList.Add(_lowercaseCharacters);
        if (characterType.HasFlag(CharacterType.UpperCase))
            characterList.Add(_uppercaseCharacters);
        if (characterType.HasFlag(CharacterType.Special))
            characterList.Add(_specialCharacters);
        var source = string.Concat(characterList);
        // 生成字符串
        var random = new Random();
        var sb = new StringBuilder(length);
        for (int i = 0; i < length; i++)
            sb.Append(source[random.Next(length)]);
        // 返回结果
        return sb.ToString();
    }
}